//app.js
import {wxLogin} from "./pages/common/netTool.js"
import Promise from "./utils/es6-promise.js"
var PATH = require("./pages/common/api-path.js");
App({
  onLaunch: function () {
    //调用API从本地缓存中获取数据
    this.getUserInfo();
  },
  globalData: {
    userInfo: null,
    // base_url : "http://t.imoduo.com:9000/moduo/",
    // base_image_url : "http://120.77.150.227:8886/"
    base_url : "http://api.imoduo.com:9000/moduo/",
    base_image_url : "http://img.imoduo.com/"
  },
  getUserInfo: function (cb, suc, parentId) {//获取code
    if (this.token()) {
      return;
    }
    var that = this;
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //调用登录接口
      wx.login({
        success: function (res) {
          that.getWxOpendId(res.code, suc, parentId) //获取openid
        }  
      });
    }
  },
  getWxOpendId: function (code, suc, parentId) {//获取openId

    var appid = 'wx9b3be3e7a4fdb27e'; //填写微信小程序appid  
    var secret = '383b1f24c58004cbf8a64842a915c56f'; //填写微信小程序secret  
    var that = this;
    var openId;
    var openUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&grant_type=authorization_code&js_code=' + code
    console.log()
    wx.request({
      url: openUrl,  
      data: {},
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        openId = res.data.openid //返回openid
        // 获取用户信息
        wx.getSetting({
          success: res => {
            if (res.authSetting['scope.userInfo']) {
              // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
              wx.getUserInfo({
                success: function (res) {
                  var user = res.userInfo;
                  var json = {
                    openid: openId,
                    unionId: openId,
                    loginType: 2,
                    nickname: user.nickName,
                    headImg: user.avatarUrl,
                    inviteId: 0
                  };
                  if (parentId) {
                    json.parentId = parentId;
                  }
                  var pages = getCurrentPages()    //获取加载的页面
                  var currentPage = pages[pages.length - 1]    //获取当前页面的对象
                  var options = currentPage.options    //如果要获取url中所带的参数可以查看options
                  if (options.parentId) {
                    json.parentId = options.parentId
                  }
                  that.wxLogin(json, suc);
                },
                fail: function (res) {
                  if (res.errMsg == 'getUserInfo:fail auth deny') {
                    wx.showModal({
                      title: '登录失败',
                      content: '您已拒绝使用微信登录，请修改授权设置，以便登录',
                      confirmText: '打开设置',
                      success: function (res) {
                        if (res.confirm) {
                          wx.openSetting({
                            success: function (res) {
                              that.getUserInfo(true, suc);
                            }
                          });
                        }
                      }
                    });
                  }
                }
              });
            }
          }
        })
      }
    })
  },
  wxLogin: function (json) {
    fetchPostApi("user/appLogin", json).then(data => {
      wx.setStorageSync('userId', data.userId)
      wx.setStorageSync('userName', data.name)
    })
  },

  token: function () {//获取登录token
    return wx.getStorageSync('userId');
  },


  //-----------------------数据请求---------------------
  fetchPostApi: function(url, params) {
    return this.fetchApi(url, params, "POST").then(data => data)
  },
  fetchApi: function (url, params, method) {
    var that = this
    url = this.globalData.base_url + url
    if (params != null) {
      params = this.moduoParams(params)
    } else {
      params = undefined
    }
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${url}`,
        data: params,
        method: method,
        header: { 'Content-Type': 'application/json'},
        success: function (res) {
          var data = res.data.data;
          var code = res.data.status;
          if (code != 1) {
            console.log('data is', res)
          }
          if (!res.data) {
            that.errorBox("维护中");
          }
          if (code == "0010") {
            that.errorBox("抱歉，微信登录正在维护中");
          }
          if (code == '1') {
            resolve(data)
          } else if (code == '0000') {
            if (that.token()) {
              that.showError("登录过时");
            }
            wx.removeStorageSync('token');
            that.getUserInfo(false, afterLogin);
          } else if (code == '1020') {
            wx.showModal({
              title: '提示',
              content: res.data.message ? res.data.message : "",
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定');
                  wx.navigateTo({
                    url: '/pages/index/parent/parent',
                  })
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          } else {

            that.errorBox(res.data.info);

          }
        },
        fail: function (res) {
          wx.hideToast();
          if (mode) {
            wx.showToast({ title: mode == 1 ? '获取失败' : '操作失败', icon: 'loading', duration: 2000, mask: "true" });
          }
        }
      })
    })
  },

  moduoParams: function (params) {
    var newParams = {}
    var secret = 'moduo@2017&sfli%87wirioew3^534rj'
    var md5 = require('./utils/md5.min.js')
    var paramStr = JSON.stringify(params)
    var str = secret + paramStr
    var sign = md5(secret + paramStr)

    newParams.apisign = sign;
    newParams['data'] = params
    return newParams
  },

  //微信展示图片数组
  showImage: function (currentIndex, urls) {
    wx.previewImage({
      current: urls[currentIndex],
      urls: urls
    });
  },
  //上传图片到微信服务器
  uploadImg: function (img, success) {
    console.log(img)
    wx.uploadFile({
      url: this.globalData.apiUrl + "/api/open/common/uploadImageTemp",
      filePath: img,
      name: 'imgFile',
      success: function (res) {
        console.log(res);
        var data = res.data;
        var json = JSON.parse(data);
        success(json.data);
      }
    })
  },

  //时间处理 yy-MM-dd
  formatDate: function (dateLong) {
    var date = new Date(dateLong);
    var month = date.getMonth() + 1;
    if (month < 10) {
      month = '0' + month;
    }
    var day = date.getDate();
    if (day < 10) {
      day = '0' + day;
    }
    return date.getFullYear() + '-' + month + '-' + day;
  },

  //时间处理 yy-MM-dd hh:mm
  formatDateTime: function (inputTime) {
    let r = /^\+?[1-9][0-9]*$/;
    if (!r.test(inputTime)) {
      return "";
    }
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute;
  },

  //-------------------------提示框-----------------------
  errorToast: function (msg) {
    wx.showToast({
      title: msg,
      duration: 2000
    });
  },
  successToast: function (msg) {
    wx.showToast({
      title: msg,
      duration: 2000
    });
  },
  showError: function (msg) {
    wx.showToast({
      title: msg,
      // icon: 'loading',
      image: '/image/error_icon.png',
      duration: 2000
    });
  },
  showSuccess: function (msg) {
    wx.showToast({
      title: msg ? msg : '',
      icon: 'success',
      duration: 2000
    });
  },
  errorBox: function (msg) {
    wx.showModal({
      title: '提示',
      content: msg?msg:'错误',
      showCancel: false
    })
  },
  tipToast: function (msg, success) {
    wx.showModal({
      title: '提示',
      content: msg?msg:'',
      success: function (res) {
        if (res.confirm) {
          success();
        }
      }
    });
  },
  showMsg: function (title, content, success) {
    wx.showModal({
      title: title,
      content: content ? content : '',
      success: function (res) {
        if (res.confirm) {
          success();
        }
      }
    });
  },

  isNull: function (param) {//对null判空
    return !param || param == '' || param == "null" || param == null;
  },
  jsonNull: function (obj) {//对null数值处理
    var json = obj;
    for (var key in json) {
      if (json[key] == null || json[key] == undefined) {
        json[key] = ""
      } else {
        json[key] = json[key];
      }
    }
    return json;
  },

  //时间处理
  formatTime: function (number, format) {
  
    var formateArr  = ['Y', 'M', 'D', 'h', 'm', 's']
    var returnArr   = []
  
    var date = new Date(number * 1000)
    returnArr.push(date.getFullYear())
    returnArr.push(this.formatNumber(date.getMonth() + 1))
    returnArr.push(this.formatNumber(date.getDate()));  
  
    returnArr.push(this.formatNumber(date.getHours()));  
    returnArr.push(this.formatNumber(date.getMinutes()));  
    returnArr.push(this.formatNumber(date.getSeconds()));  
  
    for(var i=0; i<returnArr.length; i++)  
    {
      format = format.replace(formateArr[i], returnArr[i]);
    }
    return format;  
  },
  //数据转化  
  formatNumber: function(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  },
  changeTime: function(time) {
    const dt = new Date(parseInt(time + '000'))
    const dtNow = new Date()
    if (dt.getFullYear() == dtNow.getFullYear() && dt.getMonth() == dtNow.getMonth() && dt.getDate() == dtNow.getDate() && dtNow.getTime() - dt.getTime() > 0) {
      if (parseInt((dtNow.getTime() - dt.getTime()) / (60 * 1000)) == 0) {
        return '刚刚'
      } else {
        return dtNow.getTime() > dt.getTime() + 60 * 60 * 1000 ?
          parseInt((dtNow.getTime() - dt.getTime()) / (60 * 60 * 1000)) + '小时前' :
          parseInt((dtNow.getTime() - dt.getTime()) / (60 * 1000)) + '分钟前'
      }
    } else {
      if (dtNow.getTime() - dt.getTime() < 7 * 24 * 60 * 60 * 1000 && dtNow.getTime() - dt.getTime() > 0) {
        const day = parseInt((dtNow.getTime() - dt.getTime()) / (24 * 60 * 60 * 1000)) + 1
        return day + '天前'
      } else {
        if (dtNow.getYear() == dt.getYear()) {
          return ((parseInt(dt.getMonth()) < 9 ? '0' : '') + (parseInt(dt.getMonth()) + 1)) + '-' + (parseInt(dt.getDate()) < 10 ? '0' : '') + dt.getDate()
        } else {
          return dt.getFullYear() + '-' + ((parseInt(dt.getMonth()) < 10 ? '0' : '') + (parseInt(dt.getMonth()) + 1)) + '-' + (parseInt(dt.getDate()) < 10 ? '0' : '') + dt.getDate()
        }
      }
    }
  }
})